package com.kaishengit.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kaishengit.dao.GoalDao;
import com.kaishengit.pojo.Goal;
import com.kaishengit.pojo.Project;
import com.kaishengit.pojo.Task;
import com.kaishengit.pojo.User;
import com.kaishengit.util.DateUtil;

@Service
@Transactional
public class GoalService {
	private GoalDao goalDao;

	public void save(Goal goal, User user, Project project) {
		goal.setCreatetime(DateUtil.getDate());
		goal.setUser(user);
		goal.setProject(project);
		goalDao.save(goal);
	}

	public void update(Goal goal, User user, Project project) {
		goal.setCreatetime(DateUtil.getDate());
		goal.setUser(user);
		goal.setProject(project);
		goalDao.update(goal);
	}

	public void del(int id) {
		goalDao.del(id);
	}

	public Goal findById(int id) {
		return goalDao.findById(id);
	}

	public List<Goal> findAll() {
		return goalDao.findAll();
	}

	@Autowired
	public void setGoalDao(GoalDao goalDao) {
		this.goalDao = goalDao;
	}

	public List<Goal> findByProject(Project project) {
		List<Goal> goals = goalDao.findByProject(project);
		int num = 0;
		for (Goal goal : goals) {
			int sum = 0;
			for (Task task : goal.getTasklist()) {
				sum += task.getRate();
			}
			if (sum != 0) {
				goals.get(num).setPlan(sum / goal.getTasklist().size());
			}
			num++;
		}
		return goals;
	}

}
